//
//  NSArray+Additions.m
//  OCStarterProject
//
//  Created by huaya on 2025/10/2.
//

#import "NSArray+Additions.h"

@implementation NSArray (Additions)

- (NSArray *)safeArray {
    return self ?: @[];
}

- (BOOL)isNotEmpty {
    return self.count > 0;
}

- (id)safeObjectAtIndex:(NSUInteger)index {
    if (index < self.count) {
        return [self objectAtIndex:index];
    }
    return nil;
}

- (NSString *)toJSONString {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
    if (error) {
        NSLog(@"Array to JSON error: %@", error);
        return @"";
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (NSArray *)removeDuplicates {
    NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:self];
    return [orderedSet array];
}

- (NSDictionary *)groupByKey:(NSString *)key {
    NSMutableDictionary *groupedDict = [NSMutableDictionary dictionary];
    
    for (id object in self) {
        if ([object respondsToSelector:NSSelectorFromString(key)]) {
            id keyValue = [object valueForKey:key];
            if (keyValue) {
                NSMutableArray *group = groupedDict[keyValue];
                if (!group) {
                    group = [NSMutableArray array];
                    groupedDict[keyValue] = group;
                }
                [group addObject:object];
            }
        }
    }
    
    return [groupedDict copy];
}

- (nullable id)wx_objectOrNilAtIndex:(NSUInteger)index {
    return index < self.count ? self[index] : nil;
}

@end
